import os
import unittest

from HTMLTestRunner import HTMLTestRunner

from autoframe.common.functions import open_browser
from autoframe.page.backend_login_page import Backend_login
from autoframe.page.backend_page import Backend_Page
from autoframe.common.base import *
from autoframe.page.new_commodity_page import New_Commodity
from autoframe.page.order_page import Order_Management


class LoginTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        # 打开浏览器
        driver = open_browser()
        # 创建了对象
        cls.login = Backend_login(driver)
        cls.index = Backend_Page(driver)
        cls.new_commodity = New_Commodity(driver)
        cls.order = Order_Management(driver)

    def test_01(self):
        # 输入网址
        self.login.get('http://172.16.140.57/ecshop/admin/')
        # 关闭后端登录的弹窗
        self.login.click((By.TAG_NAME, 'span'))
        # 点击跳转到后端登录页面
        self.login.click((By.ID, 'cloudLogin'))
        # 输入账号
        self.login.input_username('root')
        # 输入密码
        self.login.input_password('ecshop123')
        # 点击自动登录按钮
        self.login.remember()
        # 点击登录
        self.login.btn_login()
        # 断言登录成功
        name = self.index.text()
        self.assertEqual('root', name)

    def test_02(self):
        # 商品管理,添加新商品,确定
        self.new_commodity.skip()
        system_info = self.index.text2()
        # 断言商品添加成功
        self.assertEqual('添加商品成功。', system_info)

    def test_03(self):
        # 商品管理,添加新商品,重置
        time.sleep(2)
        self.login.refresh()
        time.sleep(2)
        self.new_commodity.skip(info='重置')
        system_info = self.index.text3()
        # 断言是否重置成功
        self.assertEqual('', system_info)

    def test_04(self):
        # 订单管理
        time.sleep(2)
        self.login.refresh()
        self.order.order()
        # 断言订单号是否相同
        self.assertEqual(self.order.order1, self.order.order2)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.login.quit(1)


if __name__ == '__main__':
    # 定位report目录
    report = os.path.abspath('../report/')
    # 创建文件名
    filename = time.strftime('%Y-%m-%d-%H-%M-%S') + '后端测试.html'
    # 写入文件地址拼接
    filepath = os.path.join(report, filename)
    # 执行用例模块地址
    discover = unittest.defaultTestLoader.discover('../case', pattern='back*')
    # 打开文件写入文件,此方法结束后会自动关闭文件
    with open(filepath, 'wb') as f:
        runner = HTMLTestRunner(
            title='Ecshop后端',  # 测试标题报告
            stream=f,  # 导入测试报告
            verbosity=2,  # 测试报告详细程度
            tester='昊昊',  # 作者名
            description='添加新商品,订单管理查看'  # 测试副标题
        )
        runner.run(discover)
